using System;
using System.Collections;
using Microsoft.Office.Interop.Outlook;

public class EventListener
{
    // Fields
    private Application application;
    private ArrayList eventSinks;
    private Explorers explorers;
    private Inspectors inspectors;
    private Shutdown shutdownHandlerDelegate;

    // Methods
    public EventListener(Application application, Shutdown shutdownHandlerDelegate)
    {
        this.application = application;
        this.shutdownHandlerDelegate = shutdownHandlerDelegate;
        this.explorers = application.Explorers;
        this.inspectors = application.Inspectors;
        this.eventSinks = new ArrayList();
        this.explorers.NewExplorer += ExplorersNewExplorer;
        this.inspectors.NewInspector += InspectorsNewInspector;
        foreach (Explorer explorer in application.Explorers)
        {
            this.ExplorersNewExplorer(explorer);
        }
        foreach (Inspector inspector in application.Inspectors)
        {
            this.InspectorsNewInspector(inspector);
        }
    }

    public void ExplorerClose()
    {
        if ((this.application.Explorers.Count <= 1) && (this.application.Inspectors.Count == 0))
        {
            this.HandleShutdown();
        }
    }

    public void ExplorersNewExplorer(Explorer explorer)
    {
        this.eventSinks.Add(explorer);
        ((ExplorerEvents_Event)explorer).Close += ExplorerClose;
    }

    private void HandleShutdown()
    {
        this.application = null;
        this.explorers = null;
        this.inspectors = null;
        this.eventSinks.Clear();
        this.eventSinks = null;
        GC.Collect();
        GC.WaitForPendingFinalizers();
        this.shutdownHandlerDelegate();
    }

    public void InspectorClose()
    {
        if ((this.application.Explorers.Count == 0) && (this.application.Inspectors.Count <= 1))
        {
            this.HandleShutdown();
        }
    }

    public void InspectorsNewInspector(Inspector inspector)
    {
        this.eventSinks.Add(inspector);
        ((InspectorEvents_Event)inspector).Close += InspectorClose;
    }

    // Nested Types
    public delegate void Shutdown();
}

